package parsers

import (
	"encoding/binary"
	"strconv"
	"time"
)

func ParseFloat64WithDefault(s string, dv float64) float64 {
	ret, err := strconv.ParseFloat(s, 64)
	if err != nil {
		return dv
	}

	return ret
}

func ParseInt64WithDefault(s string, dv int64) int64 {
	ret, err := strconv.ParseInt(s, 10, 64)
	if err != nil {
		return dv
	}

	return ret
}

func ParseIntWithDefault(s string, di int) int {
	ret, err := strconv.Atoi(s)
	if err != nil {
		return di
	}

	return ret
}

func Float64String(f float64) string {
	return strconv.FormatFloat(f, 'f', -1, 64)
}

// ParseTimeStr format '2011-1-1 1:1:1' to '2011-01-01 01:01:01'
func ParseTimeStr(s string) string {
	var layoutIn = "2006-1-2 15:4:5"
	var layoutOut = "2006-01-02 15:04:05"

	t, err := time.Parse(layoutIn, s)
	if err != nil {
		return ""
	}

	return t.Format(layoutOut)
}

func Uint64ToBytes(i uint64) []byte {
	var buf [8]byte
	binary.BigEndian.PutUint64(buf[:], i)
	return buf[:]

}

func BytesToUint64(b []byte) uint64 {
	return binary.BigEndian.Uint64(b)

}
